package com.jintian.smart.platform.system.service;

import cn.dev33.satoken.stp.StpUtil;
import com.google.common.collect.Lists;
import com.jintian.smart.base.api.security.provider.ISecurityPasswordProvider;
import com.jintian.smart.base.api.system.entity.*;
import com.jintian.smart.base.api.system.form.*;
import com.jintian.smart.kernel.common.util.SmartBeanUtil;
import com.jintian.smart.kernel.core.code.UserErrorCode;
import com.jintian.smart.kernel.core.constant.StringConst;
import com.jintian.smart.kernel.core.domain.RequestUser;
import com.jintian.smart.kernel.core.domain.ResponseDTO;
import com.jintian.smart.kernel.core.enumeration.UserTypeEnum;
import com.jintian.smart.kernel.orm.impl.AbstractEntityServiceImpl;
import com.jintian.smart.base.api.system.view.DepartmentVO;
import com.jintian.smart.base.api.system.view.EmployeeVO;
import com.jintian.smart.base.api.system.view.RoleEmployeeVO;
import com.jintian.smart.platform.system.mapper.EmployeeMapper;
import com.jintian.smart.platform.system.mapper.RoleEmployeeMapper;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.beetl.sql.core.page.PageResult;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 员工 service
 */
@Service
public class EmployeeService extends AbstractEntityServiceImpl<EmployeeMapper, EmployeeEntity> {
    @Resource
    private RoleEmployeeMapper roleEmployeeMapper;

    @Resource
    private DepartmentService departmentService;

    @Resource
    @Lazy
    private LoginService loginService;

    @Resource
    private PositionService positionService;

    @Resource
    private RoleEmployeeService roleEmployeeService;

    @Resource
    private RoleService roleService;

    @DubboReference
    private ISecurityPasswordProvider securityPasswordProvider;

    /**
     * 查询员工列表
     */
    public ResponseDTO<PageResult<EmployeeVO>> queryEmployee(EmployeeQueryForm employeeQueryForm) {
        employeeQueryForm.setDeletedFlag(0);
        List<Long> departmentIdList = new ArrayList<>();
        if (employeeQueryForm.getDepartmentId() != null) {
            departmentIdList.addAll(departmentService.selfAndChildrenIdList(employeeQueryForm.getDepartmentId()));
        }

        PageResult<EmployeeVO> employeePage = this.queryEmployee(employeeQueryForm, departmentIdList);
        if (employeePage != null && employeePage.getList() != null && employeePage.getList().size() > 0) {
            return ResponseDTO.ok(employeePage);
        }

        // 查询员工角色
        List<Long> employeeIdList = employeePage.getList().stream().map(EmployeeVO::getEmployeeId).collect(Collectors.toList());
        List<RoleEmployeeVO> roleEmployeeEntityList = employeeIdList.isEmpty() ? Collections.emptyList() : roleEmployeeMapper.selectRoleByEmployeeIdList(employeeIdList);
        Map<Long, List<Long>> employeeRoleIdListMap = roleEmployeeEntityList.stream().collect(Collectors.groupingBy(RoleEmployeeVO::getEmployeeId, Collectors.mapping(RoleEmployeeVO::getRoleId, Collectors.toList())));
        Map<Long, List<String>> employeeRoleNameListMap = roleEmployeeEntityList.stream().collect(Collectors.groupingBy(RoleEmployeeVO::getEmployeeId, Collectors.mapping(RoleEmployeeVO::getRoleName, Collectors.toList())));

        // 查询员工职位
        List<Long> positionIdList = employeePage.getList().stream().map(EmployeeVO::getPositionId).filter(Objects::nonNull).collect(Collectors.toList());
        List<PositionEntity> positionEntityList = positionIdList.isEmpty() ? Collections.emptyList() : positionService.listByIds(positionIdList);
        Map<Long, String> positionNameMap = positionEntityList.stream().collect(Collectors.toMap(PositionEntity::getPositionId, PositionEntity::getPositionName));

        employeePage.getList().forEach(e -> {
            e.setRoleIdList(employeeRoleIdListMap.getOrDefault(e.getEmployeeId(), Lists.newArrayList()));
            e.setRoleNameList(employeeRoleNameListMap.getOrDefault(e.getEmployeeId(), Lists.newArrayList()));
            e.setDepartmentName(departmentService.getDepartmentPath(e.getDepartmentId()));
            e.setPositionName(positionNameMap.get(e.getPositionId()));
        });
        return ResponseDTO.ok(employeePage);
    }

    /**
     * 新增员工
     */
    public synchronized ResponseDTO<String> addEmployee(EmployeeAddForm employeeAddForm) {
        // 校验登录名是否重复
        EmployeeEntity employeeEntity = this.getByLoginName(employeeAddForm.getLoginName(), null);
        if (null != employeeEntity) {
            return ResponseDTO.userErrorParam("登录名重复");
        }
        // 校验电话是否存在
        employeeEntity = this.getByPhone(employeeAddForm.getPhone(), null);
        if (null != employeeEntity) {
            return ResponseDTO.userErrorParam("手机号已存在");
        }
        // 部门是否存在
        Long departmentId = employeeAddForm.getDepartmentId();
        DepartmentEntity department = departmentService.getById(departmentId);
        if (department == null) {
            return ResponseDTO.userErrorParam("部门不存在");
        }
        EmployeeEntity entity = SmartBeanUtil.copy(employeeAddForm, EmployeeEntity.class);
        // 员工uid
        String employeeUid = cn.hutool.core.lang.UUID.randomUUID(true).toString(true);
        entity.setEmployeeUid(employeeUid);

        // 设置密码 随机密码
        String randomPassword = securityPasswordProvider.randomPassword();
        String generateSaltPassword = this.generateSaltPassword(randomPassword, employeeUid);
        entity.setLoginPwd(securityPasswordProvider.getEncryptPwd(generateSaltPassword));
        // 保存数据
        entity.setDeletedFlag(0);
        this.saveEmployee(entity, employeeAddForm.getRoleIdList());
        return ResponseDTO.ok(randomPassword);
    }

    /**
     * 更新员工
     */
    public synchronized ResponseDTO<String> updateEmployee(EmployeeUpdateForm employeeUpdateForm) {
        Long employeeId = employeeUpdateForm.getEmployeeId();
        EmployeeEntity employeeEntity = this.getById(employeeId);
        if (null == employeeEntity) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }
        // 部门是否存在
        Long departmentId = employeeUpdateForm.getDepartmentId();
        DepartmentEntity departmentEntity = departmentService.getById(departmentId);
        if (departmentEntity == null) {
            return ResponseDTO.userErrorParam("部门不存在");
        }
        // 检查唯一性
        ResponseDTO<String> checkResponse = checkUniqueness(employeeId, employeeUpdateForm.getLoginName(), employeeUpdateForm.getPhone(), employeeUpdateForm.getEmail());
        if (!checkResponse.getOk()) {
            return checkResponse;
        }
        EmployeeEntity entity = SmartBeanUtil.copy(employeeUpdateForm, EmployeeEntity.class);
        // 不更新密码
        entity.setLoginPwd(null);
        // 更新数据
        this.updateEmployee(entity, employeeUpdateForm.getRoleIdList());
        // 清除员工缓存
        loginService.clearLoginEmployeeCache(employeeId);
        return ResponseDTO.ok();
    }

    /**
     * 更新员工个人中心信息
     */
    public ResponseDTO<String> updateCenter(EmployeeUpdateCenterForm updateCenterForm) {
        Long employeeId = updateCenterForm.getEmployeeId();
        EmployeeEntity employeeEntity = this.getById(employeeId);
        if (null == employeeEntity) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }
        // 检查唯一性 登录账号不能修改则不需要检查
        ResponseDTO<String> checkResponse = checkUniqueness(employeeId, "", updateCenterForm.getPhone(), updateCenterForm.getEmail());
        if (!checkResponse.getOk()) {
            return checkResponse;
        }
        EmployeeEntity employee = SmartBeanUtil.copy(updateCenterForm, EmployeeEntity.class);
        // 不更新密码
        employee.setLoginPwd(null);
        // 更新数据
        this.updateById(employee);
        // 清除员工缓存
        loginService.clearLoginEmployeeCache(employeeId);
        return ResponseDTO.ok();
    }

    /**
     * 检查唯一性
     */
    private ResponseDTO<String> checkUniqueness(Long employeeId, String loginName, String phone, String email) {
        EmployeeEntity existEntity = this.getByLoginName(loginName, null);
        if (null != existEntity && !Objects.equals(existEntity.getEmployeeId(), employeeId)) {
            return ResponseDTO.userErrorParam("登录名重复");
        }
        existEntity = this.getByPhone(phone, null);
        if (null != existEntity && !Objects.equals(existEntity.getEmployeeId(), employeeId)) {
            return ResponseDTO.userErrorParam("手机号已存在");
        }
        existEntity = this.getByEmail(email, null);
        if (null != existEntity && !Objects.equals(existEntity.getEmployeeId(), employeeId)) {
            return ResponseDTO.userErrorParam("邮箱账号已存在");
        }
        return ResponseDTO.ok();
    }

    /**
     * 更新登录人头像
     */
    public ResponseDTO<String> updateAvatar(EmployeeUpdateAvatarForm employeeUpdateAvatarForm) {
        Long employeeId = employeeUpdateAvatarForm.getEmployeeId();
        EmployeeEntity employeeEntity = this.getById(employeeId);
        if (employeeEntity == null) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }
        // 更新头像
        EmployeeEntity updateEntity = new EmployeeEntity();
        updateEntity.setEmployeeId(employeeId);
        updateEntity.setAvatar(employeeUpdateAvatarForm.getAvatar());
        this.updateTemplateById(updateEntity);

        // 清除员工缓存
        loginService.clearLoginEmployeeCache(employeeId);
        return ResponseDTO.ok();
    }

    /**
     * 更新禁用/启用状态
     */
    public ResponseDTO<String> updateDisableFlag(Long employeeId) {
        if (null == employeeId) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }
        EmployeeEntity employeeEntity = this.getById(employeeId);
        if (null == employeeEntity) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }
        this.updateDisableFlag(employeeId, employeeEntity.getDisabledFlag() == 0 ? 1 : 0);
        if (employeeEntity.getDisabledFlag() == 1) {
            // 强制退出登录
            StpUtil.logout(UserTypeEnum.ADMIN_EMPLOYEE.getValue() + StringConst.COLON + employeeId);
        }
        return ResponseDTO.ok();
    }

    /**
     * 批量删除员工
     */
    public ResponseDTO<String> batchUpdateDeleteFlag(List<Long> employeeIdList) {
        if (CollectionUtils.isEmpty(employeeIdList)) {
            return ResponseDTO.ok();
        }
        List<EmployeeEntity> employeeEntityList = this.listByIds(employeeIdList);
        if (CollectionUtils.isEmpty(employeeEntityList)) {
            return ResponseDTO.ok();
        }
        // 更新删除
        List<EmployeeEntity> deleteList = employeeIdList.stream().map(e -> {
            EmployeeEntity updateEmployee = new EmployeeEntity();
            updateEmployee.setEmployeeId(e);
            updateEmployee.setDeletedFlag(1);
            return updateEmployee;
        }).collect(Collectors.toList());
        this.updateBatchById(deleteList);

        for (Long employeeId : employeeIdList) {
            // 强制退出登录
            StpUtil.logout(UserTypeEnum.ADMIN_EMPLOYEE.getValue() + StringConst.COLON + employeeId);
        }
        return ResponseDTO.ok();
    }


    /**
     * 批量更新部门
     */
    public ResponseDTO<String> batchUpdateDepartment(EmployeeBatchUpdateDepartmentForm batchUpdateDepartmentForm) {
        List<Long> employeeIdList = batchUpdateDepartmentForm.getEmployeeIdList();
        List<EmployeeEntity> employeeEntityList = this.listByIds(employeeIdList);
        if (employeeIdList.size() != employeeEntityList.size()) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }
        // 更新
        List<EmployeeEntity> updateList = employeeIdList.stream().map(e -> {
            EmployeeEntity updateEmployee = new EmployeeEntity();
            updateEmployee.setEmployeeId(e);
            updateEmployee.setDepartmentId(batchUpdateDepartmentForm.getDepartmentId());
            return updateEmployee;
        }).collect(Collectors.toList());
        this.updateBatchById(updateList);

        return ResponseDTO.ok();
    }

    /**
     * 更新密码
     */
    @Transactional(rollbackFor = Throwable.class)
    public ResponseDTO<String> updatePassword(RequestUser requestUser, EmployeeUpdatePasswordForm updatePasswordForm) {
        Long employeeId = updatePasswordForm.getEmployeeId();
        EmployeeEntity employeeEntity = this.getById(employeeId);
        if (employeeEntity == null) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }
        // 校验原始密码
        if (!securityPasswordProvider.matchesPwd(this.generateSaltPassword(updatePasswordForm.getOldPassword(), employeeEntity.getEmployeeUid()), employeeEntity.getLoginPwd())) {
            return ResponseDTO.userErrorParam("原密码有误，请重新输入");
        }
        // 新旧密码相同
        if (Objects.equals(updatePasswordForm.getOldPassword(), updatePasswordForm.getNewPassword())) {
            return ResponseDTO.userErrorParam("新密码与原始密码相同，请重新输入");
        }
        // 校验密码复杂度
        ResponseDTO<String> validatePassComplexity = securityPasswordProvider.validatePasswordComplexity(updatePasswordForm.getNewPassword());
        if (!validatePassComplexity.getOk()) {
            return validatePassComplexity;
        }
        // 根据三级等保规则，校验密码是否重复
        ResponseDTO<String> passwordRepeatTimes = securityPasswordProvider.validatePasswordRepeatTimes(requestUser, this.generateSaltPassword(updatePasswordForm.getNewPassword(), employeeEntity.getEmployeeUid()));
        if (!passwordRepeatTimes.getOk()) {
            return ResponseDTO.error(passwordRepeatTimes);
        }
        // 更新密码
        String newEncryptPassword = securityPasswordProvider.getEncryptPwd(this.generateSaltPassword(updatePasswordForm.getNewPassword(), employeeEntity.getEmployeeUid()));
        EmployeeEntity updateEntity = new EmployeeEntity();
        updateEntity.setEmployeeId(employeeId);
        updateEntity.setLoginPwd(newEncryptPassword);
        this.updateById(updateEntity);
        // 保存修改密码密码记录
        securityPasswordProvider.saveUserChangePasswordLog(requestUser, newEncryptPassword, employeeEntity.getLoginPwd());
        return ResponseDTO.ok();
    }

    /**
     * 获取某个部门的员工信息
     */
    public ResponseDTO<List<EmployeeVO>> getAllEmployeeByDepartmentId(Long departmentId) {
        List<EmployeeEntity> employeeEntityList = this.selectByDepartmentId(departmentId, 0);
        if (CollectionUtils.isEmpty(employeeEntityList)) {
            return ResponseDTO.ok(Collections.emptyList());
        }
        DepartmentVO department = departmentService.getDepartmentById(departmentId);
        List<EmployeeVO> voList = employeeEntityList.stream().map(e -> {
            EmployeeVO employeeVO = SmartBeanUtil.copy(e, EmployeeVO.class);
            if (department != null) {
                employeeVO.setDepartmentName(department.getDepartmentName());
            }
            return employeeVO;
        }).collect(Collectors.toList());
        return ResponseDTO.ok(voList);
    }


    /**
     * 重置密码
     */
    public ResponseDTO<String> resetPassword(Long employeeId) {
        EmployeeEntity employeeEntity = this.getById(employeeId);
        if (employeeEntity == null) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }
        String password = securityPasswordProvider.randomPassword();
        String saltPassword = this.generateSaltPassword(password, employeeEntity.getEmployeeUid());
        this.updatePassword(employeeId, securityPasswordProvider.getEncryptPwd(saltPassword));
        return ResponseDTO.ok(password);
    }


    /**
     * 查询全部员工
     */
    public ResponseDTO<List<EmployeeVO>> queryAllEmployee(Integer disabledFlag) {
        List<EmployeeVO> employeeList = this.selectEmployeeByDisabledAndDeleted(disabledFlag, 0);
        return ResponseDTO.ok(employeeList);
    }

    /**
     * 根据登录名获取员工
     */
    public EmployeeEntity getByLoginName(String loginName) {
        return this.getByLoginName(loginName, 0);
    }

    /**
     * 生成加盐密码
     * 格式为：[password]_[uid大写]_[uid小写]
     */
    public String generateSaltPassword(String password, String employeeUid) {
        return password + StringConst.UNDERLINE + employeeUid.toUpperCase() + StringConst.UNDERLINE + employeeUid.toLowerCase();
    }

    /**
     * 保存员工
     */
    @Transactional(rollbackFor = Throwable.class)
    public void saveEmployee(EmployeeEntity employee, List<Long> roleIdList) {
        // 保存员工 获得id
        this.getEntityMapper().insert(employee);

        if (CollectionUtils.isNotEmpty(roleIdList)) {
            List<RoleEmployeeEntity> roleEmployeeList = roleIdList.stream().map(e -> new RoleEmployeeEntity(e, employee.getEmployeeId())).collect(Collectors.toList());
            roleEmployeeService.batchInsert(roleEmployeeList);
        }
    }

    /**
     * 更新员工
     */
    @Transactional(rollbackFor = Throwable.class)
    public void updateEmployee(EmployeeEntity employee, List<Long> roleIdList) {
        // 保存员工 获得id
        this.updateById(employee);

        // 若为空，则删除所有角色
        if (CollectionUtils.isEmpty(roleIdList)) {
            roleEmployeeMapper.deleteByEmployeeId(employee.getEmployeeId());
            return;
        }

        List<RoleEmployeeEntity> roleEmployeeList = roleIdList.stream().map(e -> new RoleEmployeeEntity(e, employee.getEmployeeId())).collect(Collectors.toList());
        this.updateEmployeeRole(employee.getEmployeeId(), roleEmployeeList);
    }

    /**
     * 更新员工角色
     */
    @Transactional(rollbackFor = Throwable.class)
    public void updateEmployeeRole(Long employeeId, List<RoleEmployeeEntity> roleEmployeeList) {
        roleEmployeeMapper.deleteByEmployeeId(employeeId);
        if (CollectionUtils.isNotEmpty(roleEmployeeList)) {
            roleEmployeeService.batchInsert(roleEmployeeList);
        }
    }

    /*
     * 根据登录名查询员工
     */
    public EmployeeEntity getByLoginName(String loginName, Integer deletedFlag) {
        LambdaQuery<EmployeeEntity> query = this.getEntityMapper().createLambdaQuery().andEq(EmployeeEntity::getLoginName, loginName);
        if (deletedFlag != null) {
            query.andEq(EmployeeEntity::getDeletedFlag, deletedFlag);
        }
        return query.single();
    }

    /**
     * 通过姓名查询
     */
    public EmployeeEntity getByActualName(String actualName, Boolean deletedFlag) {
        LambdaQuery<EmployeeEntity> query = this.getEntityMapper().createLambdaQuery().andEq(EmployeeEntity::getActualName, actualName);
        if (deletedFlag != null) {
            query.andEq(EmployeeEntity::getDeletedFlag, deletedFlag);
        }
        return query.single();
    }

    /**
     * 通过手机号查询
     */
    public EmployeeEntity getByPhone(String phone, Boolean deletedFlag) {
        LambdaQuery<EmployeeEntity> query = this.getEntityMapper().createLambdaQuery().andEq(EmployeeEntity::getPhone, phone);
        if (deletedFlag != null) {
            query.andEq(EmployeeEntity::getDeletedFlag, deletedFlag);
        }
        return query.single();
    }

    /**
     * 通过邮箱账号查询
     */
    public EmployeeEntity getByEmail(String email, Boolean deletedFlag) {
        LambdaQuery<EmployeeEntity> query = this.getEntityMapper().createLambdaQuery().andEq(EmployeeEntity::getEmail, email);
        if (deletedFlag != null) {
            query.andEq(EmployeeEntity::getDeletedFlag, deletedFlag);
        }
        return query.single();
    }

    /**
     * 查询员工列表
     */
    public PageResult<EmployeeVO> queryEmployee(EmployeeQueryForm queryForm, List<Long> departmentIdList) {
        return this.getEntityMapper().queryEmployee(queryForm, departmentIdList);
    }

    /**
     * 更新单个
     */
    public void updateDisableFlag(Long employeeId, Integer disabledFlag) {
        this.getEntityMapper().createLambdaQuery().set(EmployeeEntity::getDisabledFlag, disabledFlag).andEq(EmployeeEntity::getEmployeeId, employeeId).update();
    }

    /**
     * 获取某个部门的员工
     */
    public List<EmployeeEntity> selectByDepartmentId(Long departmentId, Integer deletedFlag) {
        LambdaQuery<EmployeeEntity> query = this.getEntityMapper().createLambdaQuery().andEq(EmployeeEntity::getDepartmentId, departmentId);
        if (deletedFlag != null) {
            query.andEq(EmployeeEntity::getDeletedFlag, deletedFlag);
        }
        return query.single();
    }

    /**
     * 员工重置密码
     */
    public Integer updatePassword(Long employeeId, String password) {
        return this.getEntityMapper().createLambdaQuery().set(EmployeeEntity::getLoginPwd, password).andEq(EmployeeEntity::getEmployeeId, employeeId).update();
    }

    /**
     * 查询员工
     */
    public List<EmployeeVO> selectEmployeeByDisabledAndDeleted(Integer disabledFlag, Integer deletedFlag) {
        return this.getEntityMapper().selectEmployeeByDisabledAndDeleted(disabledFlag, deletedFlag);
    }

    /**
     * 获取某个部门的员工Id
     */
    public List<Long> getEmployeeIdByDepartmentId(Long departmentId, Integer deletedFlag) {
        LambdaQuery<EmployeeEntity> query = this.getEntityMapper().createLambdaQuery().andEq(EmployeeEntity::getDepartmentId, departmentId);
        if (deletedFlag != null) {
            query.andEq(EmployeeEntity::getDeletedFlag, deletedFlag);
        }
        query.desc(EmployeeEntity::getCreateTime);
        List<EmployeeEntity> employeeList = query.select(EmployeeEntity::getEmployeeId);
        List<Long> idList = employeeList.stream().map(EmployeeEntity::getEmployeeId).collect(Collectors.toList());
        return idList;
    }

    /**
     * 获取某批部门的员工Id
     */
    public List<Long> getEmployeeIdByDepartmentIdList(List<Long> departmentIds, Integer deletedFlag) {
        LambdaQuery<EmployeeEntity> query = this.getEntityMapper().createLambdaQuery().andIn(EmployeeEntity::getDepartmentId, departmentIds);
        if (deletedFlag != null) {
            query.andEq(EmployeeEntity::getDeletedFlag, deletedFlag);
        }
        query.desc(EmployeeEntity::getCreateTime);
        List<EmployeeEntity> employeeList = query.select(EmployeeEntity::getEmployeeId);
        List<Long> idList = employeeList.stream().map(EmployeeEntity::getEmployeeId).collect(Collectors.toList());
        return idList;
    }

    /**
     * 获取一批员工
     */
    public List<EmployeeVO> getEmployeeByIds(Collection<Long> employeeIds) {
        List<EmployeeEntity> entityList = this.getEntityMapper().createLambdaQuery().andIn(EmployeeEntity::getEmployeeId, employeeIds).desc(EmployeeEntity::getCreateTime).select();
        return SmartBeanUtil.copyList(entityList, EmployeeVO.class);
    }

    public Boolean userExistsRoleCode(String userId, String roleCode) {
        Long roleId = roleService.query().andEq(RoleEntity::getRoleCode, roleCode).single(RoleEntity::getRoleId).getRoleId();
        long count = roleEmployeeService.query().andEq(RoleEmployeeEntity::getEmployeeId, userId).andEq(RoleEmployeeEntity::getRoleId, roleId).count();
        return count > 0;
    }
}
